<div class="layuimini-container layuimini-page-anim">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">商品ID</label>
                            <div class="layui-input-inline">
                                <input id="GoodsID" type="text" name="GoodsID" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">卡密</label>
                            <div class="layui-input-inline">
                                <input id="token" type="text" name="token" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">状态</label>
                            <div class="layui-input-inline">
                                <select id="state" name="state" lay-verify="">
                                    <option value="all" selected>全部</option>
                                    <option value="unused">未使用</option>
                                    <option value="used">已使用</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                lay-filter="data-search-btn"><i class="layui-icon"></i>查询</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 生成卡密 </button>
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="export_token">导出纯卡密</button>
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="export_urltoken">导出链接卡密</button>

                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn " lay-event="delete"> 一键删除 </button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <!-- <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a> -->
        <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

    </div>
</div>

<script>
    layui.use(['form', 'table', 'miniPage', 'element', 'ajax'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            miniPage = layui.miniPage,
            request = layui.ajax,
            formdata = { gid: '', state: 'all' };

        table.render({
            elem: '#currentTableId',
            url: '/api/getCardList',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                { type: "checkbox", width: 50 },
                { field: 'id', width: 80, title: 'ID', sort: true },
                { field: 'gid', width: 80, title: '商品id' },
                { field: 'oid', width: 100, title: '订单id', sort: true },
                { field: 'token', width: 350, title: '卡密内容' },
                { field: 'uid', width: 90, title: '使用者', },
                { field: 'state', width: 100, title: '状态', sort: true },
                { field: 'addtime', title: '生成时间' },
                { field: 'endtime', title: '使用时间' },
                { title: '操作', minWidth: 100, toolbar: '#currentTableBar', align: "center" }
            ]],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: true,
            skin: 'line'
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            formdata.gid = data.field.GoodsID;
            formdata.state = data.field.state;
            var result = JSON.stringify(data.field);
            //执行搜索重载
            table.reload('currentTableId', {
                page: {
                    curr: 1
                }
                , where: {
                    searchParams: result,
                    gid: data.field.GoodsID,
                    state: data.field.state,
                    token: data.field.token
                }
            }, 'data');

            return false;
        });
        // 定义搜索函数
        function searchTable() {
            var formData = $("#searchForm").serializeArray();
            var params = {};
            $.each(formData, function () {
                params[this.name] = this.value;
            });
            table.reload('currentTableId', {
                where: params
            });
        }
        /**
         * toolbar事件监听
         */
        table.on('toolbar(currentTableFilter)', async function (obj) {
            if (obj.event === 'add') {   // 监听添加操作
                var content = miniPage.getHrefContent('page/table/add.html');

                var index = layer.open({
                    title: '生成卡密',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: 'auto',
                    maxWidth: '320px',

                    content: content,
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                const ids = data.map(({ id }) => id);
                if (ids.length > 0) {
                    layer.confirm('真的要删除选中的卡密么', async function (index) {
                        const res = await request.post('/delCardList', { ids: JSON.stringify(ids) });
                        if (res.code == 200) {
                            layer.msg("删除成功", { time: 1000, icon: 1, shade: 0.3 }, function (index) {
                            })
                            //  重载表格数据
                            table.reload('currentTableId', {
                                page: {
                                    curr: 1
                                }
                            }, 'data');

                        } else {
                            layer.msg("删除失败", { time: 1000, icon: 2, shade: 0.3 });
                        }

                        layer.close(index);
                    });
                } else {
                    layer.msg("请选择要删除的卡密", { time: 1000, icon: 2, shade: 0.3 });
                }

            } else if (obj.event === 'export_token') {
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if (data.length) {
                    const tokens = data.map(({ token }) => token);
                    const txt = tokens.join('\n');
                    // 创建一个隐藏的a标签，用于下载txt文件
                    var link = document.createElement('a');
                    link.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(txt);
                    link.download = 'data.txt';
                    link.style.display = 'none';
                    document.body.appendChild(link);
                    // 触发点击事件，下载txt文件
                    link.click();
                    // 移除a标签
                    document.body.removeChild(link);
                } else {
                    // 获取当前重载表格后的所有数据
                    const res = await request.get('/getCardList', { page: 1, limit: 1000000, gid: formdata.gid, state: formdata.state, token: formdata.token });
                    if (res.code == 0) {
                        const tokens = res.data.map(({ token }) => token);
                        const txt = tokens.join('\n');
                        // 创建一个隐藏的a标签，用于下载txt文件
                        var link = document.createElement('a');
                        link.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(txt);
                        link.download = 'data.txt';
                        link.style.display = 'none';
                        document.body.appendChild(link);
                        // 触发点击事件，下载txt文件
                        link.click();
                        // 移除a标签
                        document.body.removeChild(link);
                    } else {
                        layer.msg("导出失败", { time: 1000, icon: 2, shade: 0.3 });
                    }
                }

            } else if (obj.event === 'export_urltoken') {
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                var url = window.location.origin
                if (data.length) {
                    const tokens = data.map(({ token }) => url + '/?' + token);
                    const txt = tokens.join('\n');
                    // 创建一个隐藏的a标签，用于下载txt文件
                    var link = document.createElement('a');
                    link.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(txt);
                    link.download = 'data.txt';
                    link.style.display = 'none';
                    document.body.appendChild(link);
                    // 触发点击事件，下载txt文件
                    link.click();
                    // 移除a标签
                    document.body.removeChild(link);
                } else {
                    // 获取当前重载表格后的所有数据
                    const res = await request.get('/getCardList', { page: 1, limit: 1000000, gid: formdata.gid, state: formdata.state });
                    if (res.code == 0) {
                        const tokens = res.data.map(({ token }) => url + '/?' + token);
                        const txt = tokens.join('\n');
                        // 创建一个隐藏的a标签，用于下载txt文件
                        var link = document.createElement('a');
                        link.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(txt);
                        link.download = 'data.txt';
                        link.style.display = 'none';
                        document.body.appendChild(link);
                        // 触发点击事件，下载txt文件
                        link.click();
                        // 移除a标签
                        document.body.removeChild(link);
                    } else {
                        layer.msg("导出失败", { time: 1000, icon: 2, shade: 0.3 });
                    }
                }

            }
        });

        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
        });

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'delete') {
                layer.confirm('真的要删除该卡密么', async function (index) {
                    obj.del();
                    const res = await request.post('/delCard', { id: data.id });
                    if (res.code == 200) {
                        layer.msg("删除成功", { time: 1000, icon: 1, shade: 0.3 }, function (index) {
                        })
                    } else {
                        layer.msg("删除失败", { time: 1000, icon: 2, shade: 0.3 });
                    }

                    layer.close(index);
                });
            }
        });

    });
</script>